import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {Block, View, Image, Text, Video, WebView} from '@tarojs/components'
import {AtIcon} from 'taro-ui'
import {GetRequest} from "../../utils/tools";
import {http} from "../../utils/http";
import {
    TARO_ENV,
    RESOURCE_URL,
    GET_MP_KEY,
    APP_SCENIC_NOTICE,
    APP_SCENIC_DETAIL,
    APP_SCENIC_LIST
} from "../../constants/api";
import {user} from '../../utils/user.service';
import {h5Wx} from "../../utils/h5.service";
import {lxH5Wx} from "../../utils/lx.h5.service";
import {location} from "../../utils/location.service";
import classnames from 'classnames';
import typeList from './typeList';
import MenuNavs from "../scenicCard/components/Menus";
import MaskLayer from "./components/MaskLayer";
import MapContainer from "./components/MapContainer";
import OptionPannel from "./components/OptionPannel";
import AudioPlay from "./components/AudioPlay";
import "./index.scss";

const defaultIcon = "https://resource.ivcheng.com/upload/images/20220831/1661930803615_272.png";
const defaultIconMarker = "https://resource.ivcheng.com/upload/images/20220901/1661996573809_288.png";
const autoLocateTimerVal = 1000 * 60; // 实时定位自动播放定时器时间

export default class MapNavigation extends Component {
    state: {
        pkey: string,
        skey: string,
        scenicId: any,
        noticeTxt: string,
        currentNav: string,
        navMenus: array,
        navChildShow: boolean,
        scenicDetail: object,
        scenicSet: object,
        scenicBoundary: array,
        scenicTileImgs: array,
        scenicList: object,
        visible: boolean,
        disabledAutoExplain: boolean,
        audioVisible: boolean,
        playScenicInfo: object,
        playProgress: object,
        playAudioList: array,
        detailLayerVisible: boolean,
        detailLayerData: object,
        locationData: object,
        videoVisible: boolean,
        videoInfo: object
    } = {
        pkey: "",
        skey: "",
        scenicId: "",
        noticeTxt: "",
        currentNav: "景点",
        navMenus: [],
        allNavMenus: [],
        navChildShow: false,
        scenicDetail: null,
        scenicSet: null,
        scenicBoundary: null,
        scenicTileImgs: [],
        scenicList: null,
        visible: false,
        disabledAutoExplain: false,
        autoPlayStatus: false,
        audioVisible: false,
        playScenicInfo: {}, // 当前正在播放的信息
        playProgress: {}, // 当前正在播放的进度
        playAudioList: [], // 播放列表
        detailLayerVisible: false,
        detailLayerData: null,
        isDetailInner: true, // 是否在内部打开
        locationData: null,
        videoVisible: false,
        videoInfo: {
            url: "",
            photo: ""
        }
    }

    async UNSAFE_componentWillMount() {
        /*const nowDateTime = this.getNowDatetime();
        const locationData = Taro.getStorageSync("locationData");
        if(!locationData || (locationData && !locationData.lat && !locationData.lng && !locationData.time)) {
            this.authLocation(nowDateTime);
        }else {
            const tempLocationData = JSON.parse(locationData);
            if(new Date(nowDateTime).getTime() - new Date(tempLocationData.time).getTime() >= 1800000) {
                this.authLocation(nowDateTime);
            }
        }*/
        if(TARO_ENV === 'h5') {
            await h5Wx.getConfig();
        }else {
            //
        }
    }
    async componentDidShow() {
        /*const loginStatus = await user.checkLogin();
        !loginStatus && await user.jumpLogin();
        const _referer = encodeURIComponent(window.location.href);
        const siteHash = http.getSiteHash();
        const mpKeyRes = await http.HGet(GET_MP_KEY, {newMpKey: "", category: 1, productUuid: "", referer: _referer});
        const { pKey, skey } = mpKeyRes.data;
        this.setState({ pkey: pKey, skey });
        Taro.setStorageSync("mapPkey", pKey);
        Taro.setStorageSync("mapSkey", skey);
        Taro.removeStorageSync("wx_guide_url");*/

        this.init();
    }
    componentWillUnmount() {
        clearInterval(this.audioPlayProgressTimer);
        clearInterval(this.audioPlayTimer);
        clearInterval(this.autoLocateTimer);
    }
    componentDidHide() {
        // 隐藏后重置map组件(避免容器内出现多个canvas导致报错无法渲染)
        this.setState({
            scenicDetail: null,
            scenicSet: null,
            scenicList: null
        });
    }
    // 获取map组件 this 引用
    getMapNavigation(ref) {
        this.mapNavigationCmp = ref;
    }
    // deep clone
    deepClone(source) {
        const targetObj = source.constructor === Array ? [] : {};
        Object.keys(source).forEach(keys => {
            if(source[keys] && typeof source[keys] === 'object') {
                targetObj[keys] = this.deepClone(source[keys]);
            }else {
                targetObj[keys] = source[keys];
            }
        })
        return targetObj;
    }
    // 当前日期时间
    getNowDatetime() {
        let d = new Date();
        let year = d.getFullYear();
        let month = d.getMonth() + 1;
        let date = d.getDate();
        let hour = d.getHours();
        let minute = d.getMinutes();
        let second = d.getSeconds();
        let result = '';
        month = month < 10 ? '0' + month : month;
        date = date < 10 ? '0' + date : date;
        hour = hour < 10 ? '0' + hour : hour;
        minute = minute < 10 ? '0' + minute : minute;
        second = second < 10 ? '0' + second : second;
        result = year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
        return result;
    }
    // 获取位置信息(位置授权)
    authLocation(nowDateTime) {
        location.getLocation().then(res => {
            let locationData = {
                lat: "",
                lng: "",
                time: nowDateTime
            };
            if(res) {
                locationData = {
                    lat: res.latitude,
                    lng: res.longitude
                };
            }
            Taro.setStorageSync("locationData", JSON.stringify(locationData));
            this.setState({ locationData });
        });
    }

    // init
    init() {
        const params = Taro.getCurrentInstance().router.params;
        const { id, pkeys, skey } = params;
        let type = params.type || "景点";
        // type = type.indexOf("%") > -1 ? decodeURIComponent(type) : type;

        if(!!pkeys) Taro.setStorageSync("mapPkey", pkeys);
        const pkey = Taro.getStorageSync("mapPkey") || pkeys;
        console.log("pkeys ----------- : ", pkeys);
        console.log("mapPkey --------- : ", Taro.getStorageSync("mapPkey"));
        this.setState({ pkey, skey: skey || "", scenicId: id, currentNav: type, scenicDetail: null, scenicSet: null });
        this.getScenicDetail(pkeys, id, type);
    }
    // get notice
    getNotice = async (pkey, uuid) => {
        const res = await http.HGet(APP_SCENIC_NOTICE, {uuid, "p-key": pkey});
        if(res.data) {
            this.setState({ noticeTxt: res.data });
        }
    }
    // get scenic detail
    getScenicDetail = async (pkey, id, type) => {
        Taro.showLoading({title: "加载中", mask: true});
        const res = await http.HGet(APP_SCENIC_DETAIL, {scenic_id: id, "p-key": pkey});
        const { scenicData, setData } = res.data;
        Taro.setNavigationBarTitle({ title: setData.name || "地图导览" });
        const { latitude_left, longitude_left, latitude_right, longitude_right, map_url } = scenicData;
        const sysMenus = setData.sys_menu.split(",");
        const boundary = [[latitude_left * 1, longitude_left * 1], [latitude_right * 1, longitude_right * 1]];
        const tileImgs = map_url ? map_url.split(",") : [];
        const navMenus = [], allNavMenus = [];

        for(let j = 0, len2 = sysMenus.length; j < len2; j++) {
            const tempName = sysMenus[j];
            for(let i = 0, len = typeList.length; i < len; i++) {
                const name = typeList[i].name;
                if(tempName === name) {
                    navMenus.push(typeList[i]);
                    allNavMenus.push(typeList[i]);
                    break;
                }
            }
        }

        this.setState({
            allNavMenus,
            navMenus: navMenus.slice(0, 5),
            scenicDetail: scenicData,
            scenicSet: setData,
            scenicBoundary: boundary,
            scenicTileImgs: tileImgs
        }, () => {
            this.getNotice(pkey, scenicData.uuid)
            this.getScenicList(pkey, id, type);
        });
    }
    // get scenic list
    getScenicList = async (pkey, id, typeVal, isNavClick) => {
        const params = Taro.getCurrentInstance().router.params;
        const { listId, type } = params;

        if(type && !isNavClick) {
            typeVal = type.indexOf("%") > -1 ? decodeURIComponent(type) : type;
            this.setState({
                currentNav: typeVal
            })
        }

        Taro.showLoading({title: "加载中", mask: true});
        const res = await http.HGet(APP_SCENIC_LIST, {scenic_id: id, type: typeVal, name: "", "p-key": pkey});

        if(res.data.length === 0) {
            Taro.showToast({
                title: "暂无数据",
                icon: "none"
            })
        }

        let tempScenicInfo = null, scenicList = [];
        if(res.data.length > 0) {
            const datas = res.data;
            if(listId) {
                for(let i = 0, len = datas.length; i < len; i++) {
                    if(datas[i].id == listId) {
                        tempScenicInfo = datas[i];
                        break;
                    }
                }
            }

            // 更新图标
            for(let i = 0, len = datas.length; i < len; i++) {
                const type = datas[i].type || "";

                if(!type) {
                    datas[i].icon = defaultIcon;
                    datas[i].iconMarker = defaultIconMarker;
                }else {
                    for(let t = 0, len2 = typeList.length; t < len2; t++) {
                        if(typeList[t].name === type) {
                            datas[i].icon = typeList[t].icon;
                            datas[i].iconMarker = typeList[t].iconMarker;
                            break;
                        }
                    }
                }
            }

            scenicList = datas.map(item => ({
                ...item,
                lat: item.latitude * 1,
                lng: item.longitude * 1
            }))
        }
        this.setState({ scenicList }, () => {
            this.mapNavigationCmp.addMarkers("", scenicList);
            tempScenicInfo && this.mapNavigationCmp.readyOpenInfoWindow(tempScenicInfo, 500);
            Taro.hideLoading();
        });
    }
    // view notice
    viewNotice = () => {
        const { scenicDetail: { uuid } } = this.state;
        Taro.navigateTo({
            url: `/other/mapNavigation/Notice?uuid=${uuid}`
        })
    };
    // click nav
    handleClickNav(item) {
        const { pkey, scenicId } = this.state;
        this.setState({ currentNav: item.name });
        this.closeAudioPlay();
        this.getScenicList(pkey, scenicId, item.name, true);
    }
    // toggle nav-arrow
    toggleNavChild = () => {
        this.setState({ navChildShow: !this.state.navChildShow });
    };
    // locate
    handleLocate = () => {
        const { locationData, scenicBoundary } = this.state;
        /*if(!locationData) {
            Taro.showToast({
                title: "您当前不在景区范围内",
                icon: "none"
            });
            return;
        }
        const { lat, lng } = locationData;
        const isInBoundary = this.mapNavigationCmp.pointInBoundaryOrNot(lat, lng, scenicBoundary);
        if(!isInBoundary) {
            Taro.showToast({
                title: "您当前不在景区范围内",
                icon: "none"
            });
            return;
        }*/
        const ipLocation = new TMap.service.IPLocation();
        ipLocation.locate({}).then((result) => {
            if(result.message !== "Success") {
                Taro.showModal({
                    title: '提示',
                    content: '定位失败, 请稍后重试',
                    showCancel: false,
                })
                return;
            }
            const { lat, lng } = result.result.location;
            const isInBoundary = this.mapNavigationCmp.pointInBoundaryOrNot(lat, lng, scenicBoundary);
            if(!isInBoundary) {
                Taro.showToast({
                    title: "您当前不在景区范围内",
                    icon: "none"
                });
                return;
            }
            this.mapNavigationCmp.setMapCenter(lat, lng);
        })
    };
    // real locate
    realLocate() {
        const ipLocation = new TMap.service.IPLocation();
        return new Promise((resolve, reject) => {
            ipLocation.locate({}).then((result) => {
                resolve(result);
            })
        })
    }

    // hide
    hideOptionPannel = () => {
        this.setState({ visible: false }, () => {
            this.handleCloseDetail();
        });
    };
    // deal open option pannel
    dealOpenOptionPannel(lat, lng) {
        const { scenicBoundary } = this.state;
        let { disabledAutoExplain } = this.state;
        const isInBoundary = this.mapNavigationCmp.pointInBoundaryOrNot(lat, lng, scenicBoundary);

        if(!isInBoundary) {
            console.log("当前不在景区内");
            disabledAutoExplain = true;
        }
        this.setState({ visible: true, disabledAutoExplain });
    }
    // open option pannel
    openOptionPannel = async () => {
        /* -------------- 模拟 Start -------------- *
        const lat1 = 37.518585;
        const lng1 = 121.28365;
        this.dealOpenOptionPannel(lat1, lng1);
        return;
        * -------------- 模拟 End -------------- */

        const _this = this;
        let result = null;
        if(h5Wx.isWeiXin) {
            // 微信内JSSDK定位(准确且经度高)
            wx.ready(function () {
                wx.getLocation({
                    type: 'gcj02',
                    success: function (res) {
                        const lat = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                        const lng = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                        const speed = res.speed; // 速度，以米/每秒计
                        const accuracy = res.accuracy; // 位置精度
                        result = { lat, lng };

                        _this.dealOpenOptionPannel(result.lat, result.lng);
                    }
                })
            })
        }else {
            const ipLocateResult = await this.realLocate();
            const { result: { location: { lat, lng } } } = ipLocateResult;
            result = { lat, lng };
            this.dealOpenOptionPannel(result.lat, result.lng);
        }
    };
    // forward list
    forwardList = () => {
        const { scenicId, pkey, skey } = this.state;
        Taro.navigateTo({
            url: `/other/mapNavigation/List?id=${scenicId}&pkey=${pkey}`
        })
    }
    // play progress
    listenPlayProgress() {
        // 播放进度定时器
        this.audioPlayProgressTimer = setInterval(() => {
            if(!document.getElementById("audioPlay")) return;
            const { playProgress } = this.state;
            const autoPlayDom = document.getElementById("audioPlay");
            const { duration, currentTime } = autoPlayDom;
            const tempDuration = Math.floor(duration);
            const audioDuration = Math.floor(tempDuration / 60) + ":" + tempDuration % 60;
            const audioPlayTime = Math.floor(currentTime / duration * 100);
            const audioPlayTimeProgress = `${audioPlayTime}%`;

            const tempObj = {audioDuration, progress: audioPlayTimeProgress};
            const playProgressNew = Object.assign({}, {...playProgress}, tempObj);

            this.setState({ playProgress: playProgressNew });
            if(autoPlayDom.ended) {
                clearInterval(this.audioPlayProgressTimer);
                const playProgressNew2 = Object.assign({}, {...playProgress}, {playStatus: "play"});
                this.setState({ playProgress: playProgressNew2 });
            }
        }, 2000)
    }
    // auto play timer
    listenAutoPlay() {
        const { playScenicInfo, playAudioList } = this.state;
        this.audioPlayTimer && clearInterval(this.audioPlayTimer);
        // 自动播放定时器
        this.audioPlayTimer = setInterval(() => {
            const autoPlayDom = document.getElementById("audioPlay");
            const tempPlayList = this.deepClone(this.state.playAudioList);

            if(autoPlayDom && autoPlayDom.ended) {
                tempPlayList.splice(0, 1);
            }

            if(tempPlayList.length > 0) {
                const scenicInfo = tempPlayList[0];
                // 无当前播放 || 播放结束
                if(Object.keys(playScenicInfo).length === 0 || (autoPlayDom && autoPlayDom.ended)) {
                    this.mapNavigationCmp.getCurrentScenicInfoWindow(scenicInfo);

                    this.setState({
                        playScenicInfo: Object.assign({}, scenicInfo),
                        playAudioList: tempPlayList
                    });
                }
            }else {
                clearInterval(this.audioPlayTimer);
                this.setState({
                    audioVisible: false,
                    playScenicInfo: {},
                    playAudioList: []
                })
            }
        }, 2000);
    }
    // auto explain
    handleChangeAE = value => {
        if(value) {
            Taro.showLoading({title: "请稍等", mask: true});
            const { playScenicInfo, scenicList: markers } = this.state;
            let audioList = [], playList = []; // 所有音频, 播放列表
            markers.map(item => {
                if(item.audio_url) audioList.push(item);
            });

            // 有正在播放
            if(Object.keys(playScenicInfo).length > 0) {
                const playIdx = audioList.findIndex(item => item.id === playScenicInfo.id);
                playList = audioList.slice(playIdx);
            }else {
                playList = this.deepClone(audioList);
            }

            this.setState({
                autoPlayStatus: value,
                playAudioList: playList,
                playProgress: Object.assign({}, {playStatus: "pause"}),
                audioVisible: true
            }, () => {
                this.listenPlayProgress();
                this.listenAutoPlay();
                setTimeout(() => {
                    Taro.hideLoading();
                }, 2001)
            });
        }else {
            clearInterval(this.audioPlayTimer);
            this.setState({
                autoPlayStatus: value,
                playAudioList: []
            }, () => {
                this.listenPlayProgress();
            });
        }
    };
    // update locate-scenic
    updateLocateScenic(locateScenicInfo) {
        this.mapNavigationCmp.getCurrentScenicInfoWindow(locateScenicInfo);
        this.setState({
            playScenicInfo: locateScenicInfo,
            playProgress: Object.assign({}, {playStatus: "pause"}),
            audioVisible: true
        }, () => {
            this.listenPlayProgress();
        });
    }
    /**
    * 执行定位自动播放
    *
    * 1、定时获取实时定位（2min）
    * 2、遍历：计算与景点列表间距离(获取距离最小的景点)
    * 3、距离 < playDistance米：
        A、没有播放：自动播放
        B、有播放：
            B-1、是当前播放：不做处理
            B-2、不是当前播放：停止，开始新播放
    **/
    doLocateAutoPlayFunc() {
        const _this = this;
        const { scenicSet, scenicBoundary, playScenicInfo, scenicList: markers } = this.state;
        const distanceArr = [], distanceIdxArr = []; // 距离, 距离对应的景点下标
        const playDistance = scenicSet.automatical_play_distance || 2; // 景点播放距离(单位: 米)

        // 微信内JSSDK定位(准确且精度高)
        wx.ready(function () {
            wx.getLocation({
                type: 'gcj02',
                success: function (res) {
                    if(!_this.status) {
                        _this.status = true;
                        Taro.hideLoading();
                        Taro.showToast({title: "自动讲解已开启", mask: true, icon: "none"});
                        _this.setState({ visible: false });
                    }
                    const lat = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    const lng = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    const speed = res.speed; // 速度，以米/每秒计
                    const accuracy = res.accuracy; // 位置精度
                    // 计算景点列表坐标与实时位置的距离, 返回最小距离
                    for(let i = 0, len = markers.length; i < len; i++) {
                        const tempLat = markers[i].latitude * 1, tempLng = markers[i].longitude * 1;
                        if(markers[i].audio_url) {
                            const distance = _this.mapNavigationCmp.calcDistanceBetweenPoint(lat, lng, tempLat, tempLng);
                            distanceArr.push(distance);
                            distanceIdxArr.push(i);
                        }
                    }
                    const minDistance = Math.min(...distanceArr); // 最近距离
                    // console.log("distanceArr : ", distanceArr);
                    // console.log("minDistance : ", `与您位置最近景点的距离为: ${minDistance}米`);
                    // 距实时位置playDistance米内的景点
                    if(minDistance <= playDistance * 1) {
                        // 当前距离最近的景点
                        const currentScenicIdx = distanceIdxArr[distanceArr.indexOf(minDistance)];
                        const currentScenic = markers[currentScenicIdx];
                        let scenicOfMinDistance = null; // 距离最小的景点
                        // 有正在播放
                        if(Object.keys(playScenicInfo).length > 0) {
                            // 是当前播放
                            if(playScenicInfo.id === currentScenic.id) {
                                console.log("当前播放不做处理");
                            }else {
                                // 非当前景点播放: 更新景点播放
                                scenicOfMinDistance = Object.assign({}, currentScenic);
                                _this.updateLocateScenic(scenicOfMinDistance);
                            }
                        }else {
                            scenicOfMinDistance = Object.assign({}, currentScenic);
                            _this.updateLocateScenic(scenicOfMinDistance);
                        }
                    }
                    const isInBoundary = _this.mapNavigationCmp.pointInBoundaryOrNot(lat, lng, scenicBoundary);
                    // 离开景区
                    if(!isInBoundary) clearInterval(_this.autoLocateTimer);
                },
                fail: function(res) {
                    Taro.hideLoading();
                }
            });
        })
    }
    /**
    * 监听自动讲解开关
    **/
    handleChangeAEByLocate = async value => {
        /* -------------- 模拟 Start -------------- *
        this.handleChangeAEByLocate__MOCK(value);
        return;
        * -------------- 模拟 End -------------- */

        if(value) {
            const { scenicSet } = this.state;
            const regular_check_location = scenicSet.regular_check_location || 2;
            Taro.showLoading({title: "请稍等", mask: true});

            if(h5Wx.isWeiXin) {
                this.doLocateAutoPlayFunc();
                this.autoLocateTimer = setInterval(() => {
                    this.doLocateAutoPlayFunc();
                }, autoLocateTimerVal * regular_check_location * 1);
            }else {
                // JSAPI-IP定位
                const result = await this.realLocate();
                const { result: { location: { lat, lng } } } = result;
                console.log("JSAPI-IP定位 : ", lat, lng);
                console.log("暂不支持, 距离精度偏移太大");
                setTimeout(() => {
                    Taro.hideLoading();
                }, 1500)
            }
        }else {
            clearInterval(this.autoLocateTimer);
            this.setState({
                audioVisible: false,
                playScenicInfo: {},
            }, () => {
                this.listenPlayProgress();
            });
        }
    }
    // 模拟: 执行定位
    doLocateAutoPlayFunc__MOCK() {
        const { scenicSet, playScenicInfo, scenicList: markers } = this.state;
        const distanceArr = [], distanceIdxArr = []; // 距离, 距离对应的景点下标
        const playDistance = scenicSet.automatical_play_distance || 2; // 景点播放距离(单位: 米)

        const lat1 = 37.518585;
        const lng1 = 121.28365;
        console.log("latitude : ", lat1)
        console.log("longitude : ", lng1)
        if(!this.status) {
            this.status = true;
            Taro.hideLoading();
            Taro.showToast({title: "自动讲解已开启", mask: true, icon: "none"});
            this.setState({ visible: false });
        }

        // 计算景点列表坐标与实时位置的距离, 返回最小距离
        for(let i = 0, len = markers.length; i < len; i++) {
            const tempLat = markers[i].latitude * 1, tempLng = markers[i].longitude * 1;
            if(markers[i].audio_url) {
                const distance = this.mapNavigationCmp.calcDistanceBetweenPoint(lat1, lng1, tempLat, tempLng);
                distanceArr.push(distance);
                distanceIdxArr.push(i);
            }
        }
        console.log("distanceArr : ", distanceArr);
        const minDistance = Math.min(...distanceArr);
        console.log("minDistance : ", `与您位置最近景点的距离为: ${minDistance}米`);
        // 距实时位置playDistance米内的景点
        if(minDistance <= playDistance * 1) {
            // 当前景点
            const currentScenicIdx = distanceIdxArr[distanceArr.indexOf(minDistance)];
            const currentScenic = markers[currentScenicIdx];
            let scenicOfMinDistance = null; // 距离最小的景点
            // 有正在播放
            if(Object.keys(playScenicInfo).length > 0) {
                // 是当前播放
                if(playScenicInfo.id === currentScenic.id) {
                    //
                }else {
                    scenicOfMinDistance = Object.assign({}, currentScenic);
                    this.updateLocateScenic(scenicOfMinDistance);
                }
            }else {
                scenicOfMinDistance = Object.assign({}, currentScenic);
                this.updateLocateScenic(scenicOfMinDistance);
            }
        }
    }
    // 模拟: 监听自动讲解开关
    handleChangeAEByLocate__MOCK = async (value) => {
        const { scenicSet } = this.state;
        let regular_check_location = scenicSet.regular_check_location || 2;
        const timerVal = autoLocateTimerVal * regular_check_location * 1;
        const playTime = scenicSet.automatical_play_distance;
        console.log("timerVal : ", timerVal);
        console.log("playTime : ", playTime);

        if(value) {
            Taro.showLoading({title: "请稍等", mask: true});
            this.doLocateAutoPlayFunc__MOCK();
            this.autoLocateTimer = setInterval(() => {
                this.doLocateAutoPlayFunc__MOCK();
            }, 5000)
        }else {
            clearInterval(this.autoLocateTimer);
            this.setState({
                audioVisible: false,
                playScenicInfo: {},
            }, () => {
                this.listenPlayProgress();
            });
        }
    }
    // show tile
    handleChangeTile = value => {
        this.mapNavigationCmp.hideTiles(value);
    };
    // close AudioPlay
    closeAudioPlay = () => {
        this.setState({
            audioVisible: false,
            playScenicInfo: {},
        }, () => {
            clearInterval(this.audioPlayProgressTimer);
        });
    }
    // 控制播放
    controlPlay = (status) => {
        const autoPlayDom = document.getElementById("audioPlay");
        const { playProgress } = this.state;
        let playProgressNew = null;

        if(status === "pause") {
            autoPlayDom.pause();
            clearInterval(this.audioPlayProgressTimer);
            playProgressNew = Object.assign({}, {...playProgress}, {playStatus: "play"});
        }else {
            autoPlayDom.play();
            playProgressNew = Object.assign({}, {...playProgress}, {playStatus: "pause"});
            this.listenPlayProgress();
        }

        this.setState({ playProgress: playProgressNew });
    }
    // 监听视频
    handlePlayVideo(e) {
        const { properties } = e.geometry;
        const videoInfo = {
            url: properties.video_url,
            photo: properties.video_photo_url
        };
        this.setState({ videoInfo, videoVisible: true });
    }
    // 视频全屏
    handleVideoFullScreen(e) {
        document.querySelector(".taro-video-container").style.zIndex = 2010;
    }
    // 监听解说
    handleCommentary(e) {
        const { properties } = e.geometry;
        const playScenicInfo = Object.assign({}, {...properties}, {playStatus: "pause"});
        const playProgress = {playStatus: "pause", audioDuration: "-:-", progress: "0%"};

        this.setState({
            audioVisible: true,
            playScenicInfo: properties,
            playProgress
        }, () => {
            // this.handleChangeAE(this.state.autoPlayStatus);
            this.listenPlayProgress();
        })
    }
    /**
    * 监听导航
    *
    * @param address 是否自动选为终点(end: 自动选为终点)
    **/
    async handleLocateWalk(e, address) {
        // #API_address : https://lbs.qq.com/webApi/uriV1/uriGuide/uriWebRoute
        address = address || ""; // 是否自动选为终点
        const { scenicId, pkey, scenicSet, playScenicInfo } = this.state;
        const { properties } = e.geometry;
        // return;
        // 有正在播放自动选为终点
        if(Object.keys(playScenicInfo).length > 0) address = "end";

        /*if(scenicSet.guide_type == "1") {
            // const result = await this.realLocate();
            // const { location } = result.result;
            // const mapUri = "https://apis.map.qq.com/uri/v1/routeplan?type=walk&from=我的位置&";
            // const fromcoord = `fromcoord=${location.lat},${location.lng}&`;
            // const to = `to=${properties.name}&`;
            // const tocoord = `tocoord=${properties.lat},${properties.lng}`;
            // const uriOther = "&policy=2&referer=NUMBZ-QW4RF-CLQJI-J5A77-XIRM3-26BWY";
            // const requestURI = `${mapUri}${fromcoord}${to}${tocoord}${uriOther}`;

            // window.open(requestURI, "_blank");

            Taro.navigateTo({
                url: `/other/mapNavigation/InnerNavigate?scenicId=${scenicId}&pkey=${pkey}&id=${properties.id}&name=${properties.name}&lat=${properties.lat}&lng=${properties.lng}&address=${address}`
            })
        }else {*/
            // 外部
            const isWX = h5Wx.isWeiXin();
            if(!isWX) {
                Taro.showModal({
                    title: '提示',
                    content: '请在微信内使用',
                    showCancel: false,
                })
                return;
            }
            lxH5Wx.navigation(properties.lat, properties.lng, properties.name);
        // }
    }
    // 监听详情
    handleViewDetail(e) {
        const eObj = Object.assign({}, e);
        const { geometry: { properties: { url} } } = eObj;
        let isDetailInner = true;
        // 有外部链接
        /*if(url && url.indexOf("https") > -1 || url.indexOf("http") > -1) {
            // window.open(url, "_blank");
            isDetailInner = false;
        }else {
            isDetailInner = true;
        }*/
        this.setState({
            isDetailInner,
            detailLayerVisible: true,
            detailLayerData: eObj,
        })
    }
    // 详情里导航
    navigatInDetailLayer = () => {
        const { detailLayerData } = this.state;
        this.handleCloseDetail();
        this.handleLocateWalk(detailLayerData, "end");
    }
    // 关闭详情 & 视频
    handleCloseDetail = () => {
        this.setState({
            detailLayerVisible: false,
            detailLayerData: null,
            videoVisible: false,
            videoInfo: {
                url: "",
                photo: ""
            }
        })
    }

    render() {
        const {
            noticeTxt,
            currentNav,
            navMenus,
            allNavMenus,
            navChildShow,
            scenicDetail,
            scenicBoundary,
            scenicTileImgs,
            scenicList,
            visible,
            disabledAutoExplain,
            audioVisible,
            playScenicInfo,
            playProgress,
            detailLayerVisible,
            detailLayerData,
            isDetailInner,
            videoVisible,
            videoInfo
        } = this.state;

        return (
            <View className="map-navigation-page">
                {
                    noticeTxt &&
                    <View className="notice-infos" onClick={this.viewNotice}>
                        <View className="notice-inner">
                            <Text className="title">公告:</Text>
                            <Text>{noticeTxt}</Text>
                        </View>
                    </View>
                }
                <View className="top-area">
                    <View className="top-header">
                        <View className="nav-menu">
                            <View className="navs-block">
                                {
                                    navMenus.map((item, index) => (
                                        <View
                                            className={classnames('nav-item', {'active': currentNav === item.name})}
                                            key={index}
                                            onClick={() => this.handleClickNav(item)}
                                        >{item.name}</View>
                                    ))
                                }
                            </View>
                            {
                                allNavMenus.length > 5 &&
                                <View className="navs-arrow">
                                    <AtIcon value='chevron-down' size='30' color='#A0A5A4' onClick={this.toggleNavChild}></AtIcon>
                                </View>
                            }
                        </View>
                    </View>
                    <View className={classnames('nav-child-all', {'active': navChildShow})}>
                        {
                            allNavMenus.map((item, index) => (
                                <View
                                    className={classnames('nc-item', {'active': currentNav === item.name})}
                                    key={index}
                                    onClick={() => this.handleClickNav(item)}
                                >{item.name}</View>
                            ))
                        }
                    </View>
                </View>

                <View className="map-area">
                    <View className="tools-btn">
                        <View className="tb-item" onClick={this.openOptionPannel}>
                            <Image src="https://resource.ivcheng.com/upload/images/20220831/1661916764155_586.png" mode='aspectFit' className="tb-img" />
                            <View className="tb-title">选项</View>
                        </View>
                        <View className="tb-item" onClick={this.forwardList}>
                            <Image src="https://resource.ivcheng.com/upload/images/20220831/1661916804695_367.png" mode='aspectFit' className="tb-img" />
                            <View className="tb-title">列表</View>
                        </View>
                    </View>
                    <View className="locate-btn" onClick={this.handleLocate}>
                        <Image src="https://resource.ivcheng.com/upload/images/20220831/1661916585781_726.png" mode='aspectFit' />
                    </View>
                    {
                        scenicList &&
                        <MapContainer
                            scenicDetail={scenicDetail}
                            boundary={scenicBoundary}
                            tileImgs={scenicTileImgs}
                            scenicList={scenicList}
                            getMapNavigation={mapRef => this.getMapNavigation(mapRef)}
                            handlePlayVideo={(e) => this.handlePlayVideo(e)}
                            handleCommentary={(e) => this.handleCommentary(e)}
                            handleLocateWalk={(e, address) => this.handleLocateWalk(e, address)}
                            handleViewDetail={(e) => this.handleViewDetail(e)}
                        />
                    }
                </View>

                {/*<View className="menu-navs">*/}
                    {/*
                        scenicDetail && <MenuNavs scenicDetail={scenicDetail} idx={2} />
                    */}
                {/*</View>*/}

                {/* 遮罩 */}
                {
                    (visible || detailLayerVisible || videoVisible) &&
                    <MaskLayer visible={visible} hideOptionPannel={this.hideOptionPannel} />
                }
                {/* 选项 */}
                <OptionPannel
                    visible={visible}
                    disabledAutoExplain={disabledAutoExplain}
                    tileImgs={scenicTileImgs}
                    handleChangeAEByLocate={this.handleChangeAEByLocate}
                    handleChangeTile={this.handleChangeTile}
                />
                {/* 音频 */}
                {
                    scenicList &&
                    <AudioPlay
                        visible={audioVisible}
                        scenicInfo={playScenicInfo}
                        playProgress={playProgress}
                        controlPlay={this.controlPlay}
                        closeAudioPlay={this.closeAudioPlay}
                    />
                }

                {/* 详情展示 */}
                <View className={classnames("detail-layer", {
                    show: detailLayerVisible
                })}>
                    {
                        detailLayerData && detailLayerVisible &&
                        <Block>
                            <View className="dl-title">
                                <View className="dlt-left">
                                    <AtIcon value='map-pin' size='24' color='#A0A5A4'></AtIcon>
                                </View>
                                <View className="dlt-mid" onClick={this.navigatInDetailLayer}>点击去这里</View>
                                <View className="dlt-right">
                                    <AtIcon value='close-circle' size='30' color='#A0A5A4' onClick={this.handleCloseDetail}></AtIcon>
                                </View>
                            </View>
                            <View className="dl-cnt">
                                <Image src={detailLayerData.geometry.properties.photo_url} className="dlc-img" />
                                <View className="dlc-title">{detailLayerData.geometry.properties.name}</View>
                                <View className="dlc-texts">{detailLayerData.geometry.properties.scenic_remark || detailLayerData.geometry.properties.remark}</View>
                            </View>
                        </Block>
                    }
                </View>

                {/* 视频播放 */}
                <View className={classnames("video-layer", {
                    show: videoVisible
                })}>
                    <Video
                        src={videoInfo.url}
                        controls={true}
                        autoplay={false}
                        poster={videoInfo.photo}
                        initialTime='0'
                        id='video'
                        loop={false}
                        muted={false}
                        onFullscreenChange={(event) => this.handleVideoFullScreen(event)}
                    />
                </View>
            </View>
        )
    }
}
